import React from 'react'
import { connect } from 'dva'
import { Button } from 'antd'
import style from './index.less'

class Video extends React.Component {
    // UNSAFE_componentWillMount(){
    //     
    // }
    state = {
        vBoxId: 'local',
        pic: '',
    }

    componentDidMount(){
        const data = this.props.data
        const that = this
        function initRTC(opts){
            // 初始化
            window.RTC = new WebRTCAPI({ // eslint-disable-line
                "useCloud": 0 ,
                "userId": opts.userId,
                "userSig": opts.userSig,
                "sdkAppId": opts.sdkappid,
                "accountType": opts.accountType,
                "closeLocalMedia": opts.closeLocalMedia
            },function(){
                RTC.createRoom({  // eslint-disable-line
                    roomid : opts.roomid * 1,
                    privateMapKey: opts.privateMapKey,
                    role : "user",
                    pureAudioPush: 0,
                });
            },function( error ){
                console.error("init error", error)
            });
        
            // // 远端流新增/更新
            RTC.on("onRemoteStreamUpdate",onRemoteStreamUpdate) // eslint-disable-line
            // // 本地流新增
            RTC.on("onLocalStreamAdd",onLocalStreamAdd) // eslint-disable-line
            // // 远端流断开
            RTC.on("onRemoteStreamRemove",onRemoteStreamRemove) // eslint-disable-line
            // // 重复登录被T
            RTC.on("onKickout",onKickout) // eslint-disable-line
            // // 服务器超时
            RTC.on("onRelayTimeout",onRelayTimeout) // eslint-disable-line
            // // just for debugging
            // // RTC.on("*",function(e){ 
            // //     console.debug(e)
            // // });
        
            RTC.on("onErrorNotify", function( info ){ // eslint-disable-line
                console.error( info )
                /* info {
                    errorCode: xxxx,
                    errorMsg: "xxxxx"
                } */
            });
        }

        if(!("data" in data)){
            this.props.dispatch({
                type: 'room/redirect'
            })
            return false
        }

        initRTC({
            "userId": data.identifier,
            "userSig": data.data.userSig,
            "privateMapKey": data.data.privateMapKey,
            "sdkappid": data.appid,
            "accountType": data.accounttype,
            "closeLocalMedia": data.closeLocalMedia,
            "roomid": data.roomnum
        });


    bindEvent();
    loadMark();
    document.getElementById("clearpin").addEventListener("click", function() {//点击清除按钮
        clearMark();
    });
    
    

    var arr = [];
        var mark = {}; //创建一个对象，
        function getid(id) { //封装函数，通过id获取该id的html标签对象
            return document.getElementById(id);
        }
        function getOffset(obj) {//封装坐标函数
            var x = 0,
                y = 0;
            while(obj) {
                x += obj.offsetLeft;//offsetLeft返回的就是元素距离父元素左边的距离，单位是像素
                y += obj.offsetTop;//offsetTop返回的就是元素距离父元素上边的距离，单位是像素
                obj = obj.offsetParent;//指定的父元素
            }
            return {//返回x和y的坐标
                x: x,
                y: y
            };
        }

        function batchCss(node, ob){
            for( let i in ob ){
                node.style[i] = ob[i] 
            }
        }

        function addMark(p, x, y, text_val, index) {//封装创建小红点和输入文字内容的函数
            var div = document.createElement("div");//创建div元素
            div.id = "mark" + index;//给div元素添加id
            div.className = "mark";//给div元素添加class
            
            batchCss(div, {
                position: "absolute",
                width: "20px",
                height: "20px",
                fontSize: "0px",
                background: 'url("src/assets/td.png") no-repeat left center',
                backgroundSize:"100%" 
            })
            div.style.left = x + "px";//div的css属性
            div.style.top = y + "px";
            p.appendChild(div);//把这个div元素追加到传过来的元素的下面
            var content_p = document.createElement("p");
            content_p.className = "content_p";
            console.log("text_val::" + text_val);
            content_p.innerHTML = text_val;//给p标签添加内容
            content_p.id = "content_p" + index;
            batchCss(content_p, {
                position: "absolute",
                height: "20px",
                lineHeight: "20px",
                marginTop: "-7px",
                marginLeft: "22px",
                padding:"3px 10px 23px 10px",
                border: "1px solid blue",
                backgroundColor: "#fff"
            })
            content_p.style.left = x + "px";
            content_p.style.top = y + "px";
            p.appendChild(content_p);

        }

        function addInput(p, x, y, index) {//封装创建输入框和确认按钮的函数
            var div = document.createElement("div");
            div.id = "input_div" + index;
            div.className = "mark_input";
            div.style.position = "absolute"
            div.style.left = x + 5 + "px";
            div.style.top = y + "px";
            var inp = document.createElement("input");
            inp.id = "mark_input";
            inp.className = "text_input";
            inp.type = "text";
            inp.value = "";
            var inp2 = document.createElement("input");
            inp2.id = "sub_input";
            inp2.className = "sub_input";
            inp2.type = "submit";
            inp2.value = "OK";
            div.appendChild(inp);
            div.appendChild(inp2);
            p.appendChild(div);
            console.log(div)
        }

        function bindEvent() {
            getid("map").onclick = function(oEvent) {    //点击图片时调用
                    console.log(arr);
                // oEvent = oEvent || event;
                var container = getid("container");
                var offset = getOffset(container);      //调用getOffset函数
                console.log(offset.y);
                console.log(oEvent.clientY);
                var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
                console.log(scrollTop);  
                var x = oEvent.clientX - offset.x;      //用浏览器窗口的可视区域减去getOffset函数返回的x值
                var y = oEvent.clientY - offset.y + scrollTop;
                // arr = JSON.parse(arr);
                var i = document.getElementsByClassName('mark').length;
                addInput(container, x, y, i);
                
                getid("sub_input").onclick = function() {//点击确认按钮时调用
                     console.log(arr);
                    let text_val = getid("mark_input").value;//输入框内容
                    container.removeChild(getid("input_div" + i));//删除container元素下面的input_div
                    console.log(text_val);
                    addMark(container, x, y, text_val, i);//创建内容
                    mark.x = x;
                    mark.y = y;
                    mark.text_val = text_val;
                    arr = sessionStorage['arr']   //获取本地存储里面的值
                    if(arr !='' && arr != undefined){
                        arr = JSON.parse(arr)
                    }else{
                            arr = [];
                           console.log('本地存储没有值')
                    }
                    console.log(mark)
                    arr.push(mark);//把x，y坐标和文字内容放到数组里面
                    console.log(arr);
                    saveMark();//调用本地存储的函数

                }

            };

        }
        
        function saveMark() {//封装本地存储的函数
            arr = JSON.stringify(arr);
            console.log('保存至对话存储', arr);
            sessionStorage['arr'] = arr;
            // pin_ajax();
        }

        function loadMark() {//页面一加载的时候调用这个函数
            var arr = sessionStorage['arr']//获取本地存储里面的值
            if(arr !='' && arr != undefined){
                console.log(arr)
                arr = JSON.parse(arr)
            }else{
                    arr = [];
                   console.log('本地存储没有值')
            }
            console.log(arr)
            if(arr) {//判断本地存储里面是否有值
                var container = getid("container");
                for(var i = 0; i < arr.length; i++) {
                    console.log(arr[i])
                    addMark(container, arr[i].x, arr[i].y, arr[i].text_val, i);//在页面上创建和本地存储对应的内容
                }
            }
        }

        function clearMark() {//点击清楚标记时调用
            arr = sessionStorage['arr']   //获取本地存储里面的值
            if(arr !='' && arr != undefined){
                arr = JSON.parse(arr)
            }
            if(arr.length === 0) {
                alert('标记已全部清除')
            } else {
                var container = getid("container");
                var i = arr.length - 1;
                console.log(i);
                container.removeChild(getid("mark" + i));
                container.removeChild(getid("content_p" + i));
                arr.length = arr.length - 1;
                saveMark();
            }

        }

        function clearBorder(){
            let video = document.getElementsByTagName("video");
            for(let i=0,len=video.length;i<len;i++){
                video[i].style.border=0
            }
        }
        document.addEventListener('click',function(e){
            let node = e.target;
            that.setState({
                ...that.state,
                vBoxId: node.getAttribute("id")
            })
            // this.state.vBoxId = node.getAttribute("id");
            var tagName = node.tagName;
            if(tagName === 'VIDEO'){
                clearBorder()
                node.style.border = '2px solid #99CCFF'
            }else{
                clearBorder()
            }
            console.log(tagName)
        })

        function onRelayTimeout(msg) {
            console.error("onRelayTimeout!" + (msg ? JSON.stringify(msg) : ""));
        }

        function onKickout() {
            console.error("on kick out!");
        }

        function onRemoteStreamRemove( info ) {
            console.log( info.userId+ ' 断开了连接');
            var videoNode = document.getElementById( info.videoId );
            if( videoNode ){
                videoNode.srcObject = null;
                document.getElementById(info.videoId).parentElement.removeChild(videoNode);
            }
        }

        function onRemoteStreamUpdate( info ) {
            if (info.stream && info.stream.active === true)
            {
                var id = info.videoId;
                var video = document.getElementById(id);
                if(!video){
                    video = createVideoElement(id);
                }
                video.srcObject = info.stream;
            } else{
                console.log('欢迎用户'+ info.userId+ '加入房间');
            }
        }

        function onLocalStreamAdd(info){
            if (info.stream && info.stream.active === true)
            {
                let id = "local";
                let video = document.getElementById(id)
                if(!video){
                    createVideoElement(id, true);
                }
                video = document.getElementById(id)
                video.srcObject = info.stream;
                video.muted = true
                video.autoplay = true
                video.playsinline = true
            }
        }

        function createVideoElement( id, isLocal ){
            var videoDiv=document.createElement("div");
            videoDiv.innerHTML = '<video id="'+id+'" autoplay '+ (isLocal ? 'muted':'') +' playsinline ></video>';
            document.querySelector("#remote-video-wrap").appendChild(videoDiv);

            return document.getElementById(id);
        }
    }

    screenshots = () => {
        let that = this
        let video = document.getElementById(that.state.vBoxId)
        video.takeSnapshot(function(data){
            that.setState({
                ...that.state,
                pic: data
            })

            var container = document.getElementById('container');
            console.log("container:", container)
            // var reg = new RegExp('"',"g");
            var map = document.getElementById("map");
            // var canvasNew = document.createElement('canvas');
            var Newimage  = document.createElement('img');
            // var context   = canvasNew.getContext('2d');
            var imgData   = data;
            // var pdfPageIndex = localStorage.getItem('pageindex') ;
            var canvasWidth  = localStorage.getItem('imgWidth') || 640;
            var canvasHeight = localStorage.getItem('imgHeight') || 368;
            // console.log("pdfPageIndex", pdfPageIndex);
            // console.log("Width, Height", canvasWidth, canvasHeight);
            // console.log("canvasNew", canvasNew);
            Newimage.src = imgData;
            Newimage.style.width = "100%"
            container.style.width  = canvasWidth + 'px'
            container.style.height = canvasHeight + 'px'
            container.style.margin = "40px auto"
            map.appendChild(Newimage);
        })

        
    }

    render (){
        return(
            <div>
                <Button onClick={this.screenshots} >截屏</Button>
                <Button id="clearpin" >clear</Button>
                <Button>停止推流</Button>
                <Button>开始推流</Button>
                <div id="remote-video-wrap"></div>
                {/* <div style={{display: this.state.pic ? 'block' : 'none'}}>
                    <img src={this.state.pic} alt='截屏'/>
                </div> */}

                <div id="container" className={style.container} style={{display: this.state.pic ? 'block' : 'none'}} >
                    <div id="map" className={style.map}>
                        
                    </div>
                </div>
            </div>
        )
        
    }
};

Video.propTypes = {
};

const mapStateToProps = state => ({
    data: state.room
})


export default connect(mapStateToProps)(Video);